package com.ecnu.jiagou.damai.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/bindingRecord/{id}")
@Component
public class WebSocket {

    private static Logger log = LoggerFactory.getLogger(WebSocket.class);

    private static ConcurrentHashMap<String, Session> connections = new ConcurrentHashMap<>();

    /**
     * 打开连接
     * @param session
     * @param id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        log.info("=====接受到的地址=====" + id);
        // 接收到客户端的请求，可以做一些其他业务逻辑处理，比如可以把该IP存储到数据库
        // 避免当前服务断开后，与客户端服务失去连接
        // 这时就可以使用到预加载处理，项目当中自定义的MyApplicationRunner类
        connections.put(id, session);
    }

    /**
     * 接收消息
     * @param text
     */
    @OnMessage
    public void onMessage(String text) {

    }

    /**
     * 异常处理
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 关闭连接
     * @param id
     */
    @OnClose
    public void onClosing(@PathParam("id") String id) throws IOException {
        connections.remove(id);
    }

    /**
     * 根据id发送消息
     * @param id
     * @param text
     */
    public void send(String id, String text) {
        try {
            Session session = connections.get(id);
            if (session != null && session.isOpen()) {
                session.getAsyncRemote().sendText(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 遍历群发消息
     * @param text
     */
    public void send(String text) {
        for (ConcurrentHashMap.Entry<String, Session> entry : connections.entrySet()) {
            send(entry.getKey(), text);
        }
    }

}